from django.shortcuts import render, redirect, reverse, HttpResponse
from django.db.models import Q
from . import models
from crm.paging import Paging
from . import form
from . import operate
from rbac.service.init_permission import init_permission
import hashlib


# Create your views here.

def login(request):
    if request.session.get('is_login'):
        return redirect(reverse('my_client'))
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        md5 = hashlib.md5()
        if password:
            md5.update(password.encode('utf-8'))
        obj = models.UserProfile.objects.filter(username=username, password=md5.hexdigest(), is_active=True).first()
        if obj:
            init_permission(request, obj)
            request.session['user_id'] = obj.pk
            # 设置session关闭浏览器失效
            request.session.set_expiry(0)
            return redirect(reverse('index'))
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    return render(request, 'login.html')


def index(request):
    return render(request, 'index.html')


def reg(request):
    form_obj = form.RegForm()
    if request.method == 'POST':
        form_obj = form.RegForm(request.POST)
        if form_obj.is_valid():
            obj = form_obj.save()
            # 部门人数+1
            return redirect(reverse('login'))
    return render(request, 'reg.html', {'form_obj': form_obj})


def client(request):
    if request.method == 'POST':
        select = request.GET.get('operate')
        user_list = request.GET.getlist('user_list')
        getattr(operate, select)(request.user_obj, user_list)
    value = request.GET.get('query', '')
    q = Q(
        Q(qq__contains=value)
        | Q(name__contains=value)
        | Q(phone__contains=value)
        | Q(qq_name__contains=value)
    )
    if request.path_info == reverse('my_client'):
        client_list = models.Customer.objects.filter(q, consultant=request.user_obj)
    else:
        client_list = models.Customer.objects.filter(q, consultant__isnull=True)
    num = len(client_list)
    page = request.GET.get('page', 1)
    page = Paging(page, num, request.GET.copy(), 3, 5)
    ret = render(request, 'client.html', {'client_list': client_list[page.start:page.end], 'page_html': page.page_html})
    ret.set_cookie('url', request.path_info)
    return ret


def edit_client(request, pk=None):
    obj = models.Customer.objects.filter(pk=pk).first()
    form_obj = form.AddClient(instance=obj)
    if request.method == 'POST':
        form_obj = form.AddClient(data=request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            url = request.COOKIES.get('url')
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect(url)
    title = '编辑用户' if pk else '新增用户'
    return render(request, 'form.html', {'form_obj': form_obj, 'title': title})


def del_client(request):
    pk = request.POST.get('id')
    obj = models.Customer.objects.filter(pk=pk).first()
    if obj:
        obj.delete()
    return HttpResponse('del')


def logout(request):
    request.session.delete()
    return redirect(reverse('login'))


def follow_client(request, customer_id=0):
    if customer_id:
        follow_list = models.ConsultRecord.objects.filter(customer_id=customer_id, delete_status=False).order_by(
            '-date')
    else:
        follow_list = models.ConsultRecord.objects.filter(
            consultant=request.user_obj,
            delete_status=False
        ).order_by('-date')
    page = request.GET.get('page', '1')
    num = len(follow_list)
    page = Paging(page, num, request.GET.copy(), 5, 5)
    return render(request, 'follow_client.html',
                  {'follow_list': follow_list[page.start:page.end], 'page_html': page.page_html,
                   'customer_id': customer_id})


def edit_follow(request, pk=None, customer_id=None):
    obj = models.ConsultRecord.objects.filter(pk=pk).first()
    form_obj = form.EditFollow(request, customer_id=customer_id, instance=obj)
    if request.method == 'POST':
        form_obj = form.EditFollow(request, customer_id=customer_id, data=request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('follow_client')
    title = '编辑记录' if pk else '新增记录'
    return render(request, 'form.html', {'form_obj': form_obj, 'title': title})
